package when3meet.controller;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import when3meet.model.ClientInfo;
import when3meet.model.User;
import when3meet.view.KickUserButton;
import xml.Message;

/**
 * This controller handle join response from server, store other user's info
 * into local model, so we could calculate the maximum allowed edges for
 * terminate condition.
 * 
 * @author Xi
 * 
 */
public class JoinController {
	/**
	 * Get user's info, store it in to local model and display in UI
	 * 
	 * @param response
	 */
	public void process(Message response) {

		Node update = response.contents.getFirstChild();
		NodeList children = update.getChildNodes();
		NamedNodeMap map = update.getAttributes();

		String id = map.getNamedItem("id").getNodeValue();
		User[] temp = ClientInfo.getInstance().getUsers();

		User[] users;
		if (temp == null)
			users = new User[1];
		else {
			users = new User[temp.length + 1];
			for (int i = 0; i < temp.length; i++)
				users[i] = temp[i];
		}

		ClientInfo ci = ClientInfo.getInstance();

		if (ci.getEventID() == id || ci.getEventID().equals(id)) {

			for (int i = 0; i < children.getLength(); i++) {
				Node n = children.item(i);
				NamedNodeMap tempMap = n.getAttributes();
				if (n.getNodeName().equalsIgnoreCase("user")) {
					String name = tempMap.getNamedItem("name").getNodeValue();
					String password = tempMap.getNamedItem("password").getNodeValue();

					User u = new User(name, password);
					users[users.length - 1] = u;
				}
			}

			ci.setUsers(users);

			KickUserButton[] kickButtons = ci.getKickBtn();
			for (int i = 0; i < ci.getUsers().length; i++) {
				try {
					kickButtons[i].setText(ci.getUsers()[i].name);
					kickButtons[i].setVisible(true);
				} catch (java.lang.NullPointerException e) {

				}
			}
			ci.setKickBtn(kickButtons);
		}
	}
}
